package controllers

import (
	"lao-a/models"
	"lao-a/models/user"
	"net/http"
	"strings"

	"github.com/astaxie/beego"
)

const (
	REQ_CLIENT_DEFAULT = "pc"
	REQ_CLIENT_WECHAT  = "wechat"
)

func (c *BaseController) auth() {
	// TODO
	c.SetSession("PlatID", "0383c3a5-41b9-4770-bafc-8cc4946873d0")

	c.checkRequestClient()
	c.wechatAuth()

	if !c.needAuth() {
		return
	}

	userId, _ := c.GetSession(SESSION_USER).(int)
	dao := user.NewDAO(c.Context)

	// code, err := dao.CheckUserRoute(userId, path, method)
	// if err != nil {
	// 	c.ResponseJson(err, code)
	// }

	if userId > 0 {
		userDetail, err := dao.GetUserById(userId)

		if err != nil {
			c.ResponseJson(err, http.StatusInternalServerError)
		}

		if userDetail == nil {
			c.ResponseJson(
				"用户不存在, 请重新登录",
				http.StatusUnauthorized,
			)
		}

		c.Context.User = userDetail
	} else {
		c.ResponseJson(
			"用户不存在, 请重新登录",
			http.StatusUnauthorized,
		)
	}
}

func (c *BaseController) needAuth() bool {
	commApiPrefix := beego.AppConfig.String("CommonApiPrefix")
	authApiPrefix := beego.AppConfig.String("AuthApiPrefix")

	if strings.HasPrefix(c.Ctx.Request.URL.Path, authApiPrefix) {
		return true
	}

	if strings.HasPrefix(c.Ctx.Request.URL.Path, commApiPrefix) {
		return false
	}

	return false
}

// wechatAuth 微信相关
func (c *BaseController) wechatAuth() {
	reqCli, _ := c.Context.Box["ReqestClient"].(string)
	if reqCli != REQ_CLIENT_WECHAT {
		return
	}

	wechatID, _ := c.GetSession("wechatID").(string)
	if wechatID == "" {
		// TODO
		return
	}

	platID, _ := c.GetSession("PlatID").(string)
	if platID != "" {
		c.Context.Box["PlatID"] = platID
		return
	}

	assAcc, err := models.GetPlatIDBy(models.ACCTYPE_WECHAT, wechatID)
	if err != nil {
		c.ResponseJson(err, http.StatusInternalServerError)
	}

	c.SetSession("PlatID", assAcc.PlatId)
	c.Context.Box["PlatID"] = assAcc.PlatId
}

func (c *BaseController) checkRequestClient() {
	reqCli := REQ_CLIENT_DEFAULT

	wxUA := strings.ToLower("MicroMessenger")
	userUA := strings.ToLower(c.Ctx.Input.UserAgent())

	if strings.Index(userUA, wxUA) > -1 {
		reqCli = REQ_CLIENT_WECHAT
	}

	c.Context.Box["RequestClient"] = reqCli
}
